const DB = require('../core/DB')

const {
    Op
} = require('sequelize')
const article = require('../models/article')

DB.tag_article.belongsTo(DB.tag)
DB.tag.hasMany(DB.tag_article)


class TagController {
    /* ------------------------- 暂时不用 可代替 标签分布 饼图 -------------------------------*/
    async getTagPie(ctx) {

        let data = await DB.tag.findAll({
            include: DB.tag_article
        })

        global.Response.success(ctx, undefined, data)
    }

    /* ------------------------- ok 获取指定标签下的文章数目 -------------------------------*/
    async listTagDetail(ctx) {
        // 参数
        let {
            id,
            page = 1,
            size = 10,
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.tag_article.findAndCountAll({
            where: {
                tagId: id
            },
            offset: (page - 1) * size,
            limit: size,
            order: [
                ['id', 'DESC']
            ],
            include: DB.article
        })

        for (let article of rows) {
            let articleId = article.get('articleId')
            let t_a = await DB.tag_article.findAll({
                where: {
                    articleId
                },
                include: DB.tag
            })

            let arr = []
            for (let v of t_a) {
                arr.push(v.get('tag'))
            }

            article.dataValues.tags = arr
        }

        const data = {
            rows,
            meta: {
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        global.Response.success(ctx, undefined, data)
    }

    /* ------------------------- ok 编辑标签 -------------------------------*/
    async updateTag(ctx) {
        // 参数
        const {
            id,
            name,
            status,
            sort,
            mark
        } = ctx.request.body

        console.log(ctx.request.body)

        await DB.tag.update({
            name,
            status,
            sort,
            mark
        }, {
            where: {
                id
            }
        }) // return [0] [1]

        global.Response.success(ctx)

    }


    /* ------------------------------------------------ ok 新增标签 ---------------------------------------------------*/
    async createTag(ctx) {
        // 参数
        const {
            name, // 标签名
            status = 1, // 显示
            sort = 1, // 排序
            mark = 0 // 标记
        } = ctx.request.body

        const [obj, created] = await DB.tag.findOrCreate({
            where: {
                name,
            },
            defaults: {
                status,
                sort,
                mark,
                createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
            }
        })

        if (created) {
            global.Response.success(ctx, '创建成功', obj)
        } else {
            global.Response.exist(ctx, '该标签已存在')
        }
    }

    /* ------------------------- ok 搜索标签 -------------------------------*/
    async searchTag(ctx){
        let {key = '',status = 1} = ctx.query

        let tags = await DB.tag.findAll({
            where: {
                name: {
                    [Op.like]: `%${key}%`
                },
                status:{
                    [Op.in]: status ? [status] : [0, 1, 2] // 审核状态
                }
            },
            order: [
                ['sort', 'DESC']
            ]
        })

        for (let tag of tags) {
            let tagId = tag.get('id')
            let articleCount = await DB.tag_article.count({
                where: {
                    tagId
                }
            })
            tag.dataValues.articleCount = articleCount
        }

        global.Response.success(ctx, undefined, tags)
    }

    /* ------------------------- ok 获取所有标签 及其各文章数 -------------------------------*/
    async listTag(ctx) {

        let tags = await DB.tag.findAll({
            order: [
                ['sort', 'DESC']
            ],
        })

        for (let tag of tags) {
            let tagId = tag.get('id')
            let articleCount = await DB.tag_article.count({
                where: {
                    tagId
                }
            })
            tag.dataValues.articleCount = articleCount
        }

        global.Response.success(ctx, undefined, tags)
    }



    /* ------------------------- ok 删除标签 -------------------------------*/
    async deleteTag(ctx) {
        const {id} = ctx.query

        await DB.tag_article.destroy({
            where: {
                tagId: id
            },
        })

        await DB.tag.destroy({
            where: {
                id
            },
        })

        global.Response.success(ctx, '删除成功')
    }


}

module.exports = new TagController